"""
测试问答功能脚本
用于验证 DeepSeek API 集成是否正常工作
"""
import os
import sys
import django

# 设置控制台编码为 UTF-8
if sys.platform == 'win32':
    import codecs
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')

# 设置 Django 环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from apps.qa.services import RAGService


def test_basic_qa():
    """测试基本问答功能"""
    print("=" * 60)
    print("测试 1: 基本问答（无 RAG）")
    print("=" * 60)

    rag_service = RAGService()

    # 模拟用户对象（实际使用时需要真实的用户对象）
    class MockUser:
        id = 1
        username = "test_user"

    user = MockUser()

    # 测试问题
    question = "什么是Python中的装饰器？"

    print(f"\n问题: {question}\n")

    try:
        result = rag_service.generate_answer(
            question=question,
            user=user,
            use_rag=False  # 不使用 RAG
        )

        print("回答:")
        print("-" * 60)
        print(result['answer'])
        print("-" * 60)
        print(f"\n模型: {result['model']}")
        print(f"Token 使用: {result['tokens']}")
        print(f"检索文档数: {len(result['retrieved_docs'])}")
        print("\n✅ 测试通过！DeepSeek API 调用成功！\n")

    except Exception as e:
        print(f"\n❌ 测试失败: {str(e)}\n")


def test_rag_qa():
    """测试 RAG 问答功能"""
    print("=" * 60)
    print("测试 2: RAG 问答（需要知识库）")
    print("=" * 60)
    print("\n注意: 此测试需要先创建知识库和上传文档")
    print("如果没有文档，将回退到普通问答模式\n")

    rag_service = RAGService()

    class MockUser:
        id = 1
        username = "test_user"

    user = MockUser()

    question = "Django中如何配置数据库？"

    print(f"问题: {question}\n")

    try:
        result = rag_service.generate_answer(
            question=question,
            user=user,
            knowledge_base_id=1,  # 假设知识库ID为1
            use_rag=True,
            top_k=3
        )

        print("回答:")
        print("-" * 60)
        print(result['answer'])
        print("-" * 60)
        print(f"\n模型: {result['model']}")
        print(f"Token 使用: {result['tokens']}")
        print(f"检索文档数: {len(result['retrieved_docs'])}")

        if result['retrieved_docs']:
            print("\n检索到的文档:")
            for i, doc in enumerate(result['retrieved_docs'], 1):
                print(f"  {i}. {doc['title']} (相关度: {doc['score']})")

        print("\n✅ RAG 测试完成！\n")

    except Exception as e:
        print(f"\n❌ 测试失败: {str(e)}\n")


def test_multiple_questions():
    """测试连续问答"""
    print("=" * 60)
    print("测试 3: 连续多轮问答")
    print("=" * 60)

    rag_service = RAGService()

    class MockUser:
        id = 1
        username = "test_user"

    user = MockUser()

    questions = [
        "Python是什么？",
        "如何学习Django？",
        "什么是RESTful API？"
    ]

    for i, question in enumerate(questions, 1):
        print(f"\n第 {i} 轮问答")
        print(f"问题: {question}")

        try:
            result = rag_service.generate_answer(
                question=question,
                user=user,
                use_rag=False
            )

            print(f"回答: {result['answer'][:100]}...")
            print(f"Token: {result['tokens']}")
            print("✅ 成功\n")

        except Exception as e:
            print(f"❌ 失败: {str(e)}\n")


if __name__ == "__main__":
    print("\n")
    print("╔" + "=" * 58 + "╗")
    print("║" + " " * 15 + "先锋小科 - 问答功能测试" + " " * 16 + "║")
    print("╚" + "=" * 58 + "╝")
    print("\n")

    # 运行测试
    test_basic_qa()

    input("\n按回车键继续测试 RAG 功能...")
    test_rag_qa()

    input("\n按回车键继续测试连续问答...")
    test_multiple_questions()

    print("\n" + "=" * 60)
    print("所有测试完成！")
    print("=" * 60 + "\n")
